#-*- coding: utf-8 -*-
#接口调用方法，请求对方的
import time
import urllib,traceback

import ProtocolHelper
isTest=0
if not isTest:
     from websys import  fun
     from websys.models import  (ServerInfo)
import ujson
import requests
from gm_site import settings
# server_id = "test1"
# server_url="192.168.0.128:8106"
# server_id = "_5wan1"
# server_url="123.207.52.239:8105"

#获取全部的服信息，{服号:ip:端口,"test1":"192.168.0.128:8106","_5wan1":"123.207.52.239:8105"}
global ServerList
ServerList={"测试":"123.207.52.239:9100,1"}
if not isTest:
     ServerList={}
def initServer():
     if not ServerList:
          tarr=ServerInfo.objects.all().values('pf','host','port','server_id')
          for ii_item in tarr:
               ServerList[ii_item['pf']]='%s:%s,%s'%(ii_item['host'],int(ii_item['port'])+100,str(ii_item['server_id']))
initServer()

#统一接口
CALLID=1
INTERFACE_ID='oss'
#服务器的ip:端口，服号，方法名，参数
def getResult(server_id,urls,funname):
     global ServerList
     if str(server_id) not in ServerList:
          return -101
     #f_url =urls
     server_url=ServerList[server_id].split(',')[0]
     server_ids=ServerList[server_id].split(',')[1]
     if funname=='gm':
          f_url=funname+urls+'&serverid=%s'%server_ids
     else:
          f_url = funname +urls
     now_ts = time.time()
     _key = str(CALLID)+":"+str(int(now_ts))#可固定
     # data = [{"m":funname,#接口名
     #      "c":CALLID,
     #      "p":params,#参数
     #      "st":now_ts}]
     try:
          url = "http://%s/"%server_url+f_url
          print(url)
          #ret = urllib.urlopen(url).read()
          ret = requests.get(url)
          #result = ProtocolHelper.Decode(ret, INTERFACE_ID)[0]['p']
          #print 'getResult--->',result
          #result=[{'p':'data':[],'r':0}] r为0成功
          if str(ret.text)=='success':
               return 1
          else:
               ret=ret.json()
               return ret['result']
     except:
          if isTest:
               print traceback.format_exc()
          else:
               fun.add_log_err(traceback.format_exc())#后期人工调用
          return -99

#批量服处理
def getResult_Batch(ser_arr,urls,funname):
     ok_num=0
     for ii_id in ser_arr:
          code=getResult(ii_id,urls,funname)
          print code,'--getResult_Batch--',
          if code==1:
               ok_num +=1
     return ok_num


def getResult2(urls,funname):
     f_url = funname + urls
     #ip_port =settings.ip
     ip_port = settings.ip
     if str(funname)=='gm_charge':
         ip_port = settings.ip_two
          #ip_port =settings.ip_two
     try:
          url = "http://%s/" % (ip_port) + f_url
          print(url)
          # ret = urllib.urlopen(url).read()
          ret = requests.get(url)
          # result = ProtocolHelper.Decode(ret, INTERFACE_ID)[0]['p']
          # print 'getResult--->',result
          # result=[{'p':'data':[],'r':0}] r为0成功
          #print '-------------------',eval(ujson.dumps(ret.text))
          if str(ret.text) == 'success':
               return 1
          else:
               if eval(ujson.dumps(ret.text))=='{"result":insert}' or eval(ujson.dumps(ret.text))=='{"result":erase}':
                    print 'here'
                    return 1
               else:
                    ret = ret.json()
                    return ret['result']
     except:
          if isTest:
               print traceback.format_exc()
          else:
               fun.add_log_err(traceback.format_exc())  # 后期人工调用
          return -99

def getResult_Batch2(urls, funname):
     ok_num = 0
     code = getResult2(urls, funname)
     print code, '--getResult_Batch--',
     if code == 1:
          ok_num += 1
     return ok_num
#某个服务调用返回
def getResult_One(ser_id,params,funname):
     return getResult(ser_id,'EXTERNAL_'+funname,params)



'''
管理员发送邮件
EXTERNAL_SENDMAIL
args: [ser_arr, playerIds, title, content,items,state,level,vip_level,arena_rank]
   管理员发送邮件
'''
def gm_send_mail(ser_arr, playerIds, title, content,items,state,level,vip_level,arena_rank):
     urls=".php?title=%s&content=%s&items=%s&state=%d&playerIds=%s&level=%s&vip_level=%s&arena_rank=%s"%(urllib.quote(str(title)),urllib.quote(str(content)),items,state,playerIds,level,vip_level,arena_rank)
     return getResult_Batch(ser_arr,urls,'gm_send_mail')




'''
管理员发送道具
EXTERNAL_SENDMAIL
args: [ser_arr, user, gold, silver,datafrom,itemid,count,stage,main_quest]
   管理员发送道具
'''
def gm_send_prop(ser_arr, user, gold, silver,datafrom,itemid,count,stage,main_quest):
     urls=".php?user=%s&gold=%s&silver=%s&datafrom=%d&itemid=%s&count=%s&stage=%s&main_quest=%s"%(urllib.quote(str(user)),gold,silver,datafrom,itemid,count,stage,main_quest)
     return getResult_Batch(ser_arr,urls,'gm')



'''
封号把控
EXTERNAL_LOGIN_SWITCH_UID
args: [ser_arr,playerId,login_state]
login_state:传1 为封号，0为解封
'''
def gm_ban_login(ser_arr,playerId,login_state):
     urls = ".php?playerId=%s&login_state=%s"%(playerId,login_state)
     return getResult_Batch(ser_arr,urls,'gm_ban_login')





'''
禁言管理
EXTERNAL_FORBID_SPEAK
args: [_uid,_timer]
'''
def gm_ban_chat(ser_arr,playerId,chat_state):
     urls = ".php?playerId=%s&chat_state=%s" % (playerId, chat_state)
     return getResult_Batch(ser_arr,urls,'gm_ban_chat')





#新增公告
#参数: ["内容", "all", int(消息id), int(开始时间戳), int(结束时间戳), int(排序值)]
def gm_broadcast_notice(ser_arr,serial_no,state,begin_utc,end_utc,seconds,content,effect):
     urls=".php?serial_no=%d&state=%d&begin_utc=%s&end_utc=%s&seconds=%s&content=%s&effect=%s"%\
          (int(serial_no),int(state),begin_utc,end_utc,seconds,urllib.quote(str(content)),effect)
     return getResult_Batch(ser_arr,urls,"gm_broadcast_notice")



#修改公告
#参数: ["内容", "all", int(消息id), int(开始时间戳), int(结束时间戳), int(排序值)]
def gm_broadcast_notice2(ser_arr,serial_no,state,begin_utc,end_utc,seconds,content):
     urls = ".php?serial_no=%d&state=%d&begin_utc=%s&end_utc=%s&seconds=%s&content=%s" % (
          int(serial_no), int(state), begin_utc, end_utc, seconds, urllib.quote(str(content)))
     return getResult_Batch(ser_arr,urls,"gm_broadcast_notice")



#修改公告状态
#参数: ["内容", "all", int(消息id), int(开始时间戳), int(结束时间戳), int(排序值)]
def gm_broadcast_notice3(ser_arr,serial_no,state,effect):
     urls = ".php?serial_no=%d&state=%d&effect=%s" % (
          int(serial_no), int(state), effect)
     return getResult_Batch(ser_arr,urls,"gm_broadcast_notice")





#修改玩家信息
def gm_role_adjust(ser_arr,playerId, nickname, level, gold, silver, exp, prestige, vip_level, vip_exp, hero_exp, soul, piece_ore):
    urls =".php?playerId=%s&nickname=%s&level=%d&gold=%d&silver=%d&exp=%d&prestige=%d&vip_level=%d&vip_exp=%d&hero_exp=%d&soul=%d&piece_ore=%d"%(
        playerId,urllib.quote(str(nickname)),level,gold,silver,exp,prestige,vip_level,vip_exp,hero_exp,soul,piece_ore)
    return getResult_Batch(ser_arr,urls,"gm_role_adjust")




#新增登录公告
def gm_send_notice(content):
     urls = ".php?content=%s"%(urllib.quote(str(content)))
     return getResult_Batch2(urls,'gm_send_notice')

#充值
def gm_charge(ser_arr,playerId,charge_money,order_num,charge_id,state):
     urls = ".php?playerId=%s&charge_money=%s&order_num=%d&charge_id=%d&state=%d"%(playerId,charge_money,order_num,charge_id,state)
     return getResult_Batch(ser_arr,urls,'gm_charge')



#黑名单
def user_black(userid):
     urls =".php?userid=%s"%(userid)
     return getResult_Batch2(urls,'user_black')




#白名单
def usergm(userid,gm):
     urls = ".php?userid=%s&gm=%s" % (userid,gm)
     return getResult_Batch2(urls, 'usergm')



#修改服务器属性
def set_server_list(ServerID,IsVisible,IsNew,IsHot,IsStop,OpenUtc):
     urls = ".php?ServerID=%d&IsVisible=%d&IsNew=%d&IsHot=%d&OpenUtc=%d&IsStop=%d" % (ServerID, IsVisible, IsNew, IsHot, OpenUtc,IsStop)
     return getResult_Batch2(urls, 'set_server_list')




'''
"EXTERNAL_DELSCROLLNOTES"
删除公告
args: [msgid] //公告ID，多条可用逗号分隔
'''
def DELSCROLLNOTES(ser_arr,msgid):
     params=[msgid]
     return getResult_Batch(ser_arr,params,"DELSCROLLNOTES")





'''
查询用户信息
EXTERNAL_USER_INFO
args: [uids]
    查询用户信息
    @param uid: str uid
    '''
def USER_INFO(ser_id,uid):
     params=[uid]
     code,res= getResult_One(ser_id,params,'USER_INFO')
     return {'code':code,'res':res}

'''
模糊查询用户信息
"EXTERNAL_SEARCH_NAME"
args: [target]
    模糊查询用户信息
    @param target :str 查询名字
    '''
def SEARCH_NAME(ser_id,target):
     params=[target]
     code,res= getResult_One(ser_id,params,'SEARCH_NAME')
     return {'code':code,'res':res}





'''
从玩家背包删除道具
"EXTERNAL_DELITEMS"
args: [uids, items]
    从玩家背包删除道具
    @param uids: str uid集合以逗号分割
    @param items: dict 道具信息  数据如：{id: num}
'''
def DELITEMS(ser_arr,uids,items):
     params = [uids,items]
     return getResult_Batch(ser_arr, params, 'DELITEMS')
#测试
# start = time.time()
# end = start + 60#*60*24*7
# print AddScrollNotes(["_5wan1"],"chong测试跑马灯：123456789（送红包）",2,start,end,12)




